<?php

namespace app\common\service;

use think\Exception;
use turbo\Miniapp;
use claviska\SimpleImage as Image;

use app\common\model\User;

class Invite
{

    const FILE_BASE = ROOT_PATH . 'public/assets/img/invite.png';

    const FILE_DIR = ROOT_PATH . 'public/invite/';

    /**
     * 邀请图片
     */
    public static function createInviteImg(User $user, $update = false)
    {
        $avatar = $user->avatar;
        if (!$avatar) {
            throw new Exception("Cannot get User's avatar");
        }
        
        $dir = self::FILE_DIR . substr($user->id, 0, 1) . '/';

        $fileName = $dir . $user->id . '.jpg';

        if ($update || !file_exists($fileName)) {
            if (!is_dir($dir)) {
                mkdir($dir, 755, true);
            }
            if(!file_exists($fileName)){
                touch($fileName);
            }

            // if (extension_loaded('Imagick')) {
            //     Image::configure(array('driver' => 'imagick'));
            // }

            try {
                $image = new Image();

                $avatarImg = (new Image())->fromFile($avatar)->resize(140, 140);
                //
                $qrcode = (new Image())->fromFile(self::getUserMiniappCode($user->id))->resize(175, 175);

                $res = $image
                    ->fromFile(self::FILE_BASE)
                    ->autoOrient()
                    ->overlay($avatarImg, 'top right', 1, -30, 40) 
                    ->overlay($qrcode, 'bottom right', 1, -70, -233) 
                    ->toFile( $fileName, 'image/jpeg');

            } catch (\Exception $e) {
                // Handle errors
                unlink($fileName);
                throw $e;
            }

            if (!$res) {
                throw new Exception("Fail to save");
            }
        }

        return $fileName;
    }


    public static function getUserMiniappCode($user_id){

        $dir = self::FILE_DIR . substr($user_id, 0, 1) . '/';

        $fileName = $dir . $user_id . '_qrcode.jpg';

        if(!file_exists($fileName)){

            if (!is_dir($dir)) {
                mkdir($dir, 755, true);
            }
            touch($fileName);
            try {
                $data = Miniapp::getMiniAppQrcode('share_from_'.$user_id);
            } catch (\Exception $e) {
                unlink($fileName);
                if(strpos($e->getMessage(),'invalid page')!==false){
                    return 'https://res.wx.qq.com/wxdoc/dist/assets/img/WXACode.fa3d686a.png';
                }
                throw $e;
            }
            file_put_contents($fileName, $data);
        }
        return $fileName;
    }
    
}
